import 'package:flutter/material.dart';
import 'package:flutter_base/base/widget/base_get_builder.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:flutter_base/generated/assets.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_base/utils/utils_widget.dart';
import 'package:flutter_base/widgets/appbar/common_app_bar.dart';
import 'package:flutter_base/widgets/button/common_button.dart';
import 'package:flutter_base/widgets/dialog/share_bottom_sheet.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_base/widgets/image/image_view.dart';
import 'package:flutter_base/widgets/image/circle_avatar_widget.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'test_detail_logic.dart';
import 'widgets/test_keyword_tag_block.dart';
import 'widgets/test_matching_result_block.dart';
import 'widgets/test_radar_chart_block.dart';
import 'widgets/test_multi_dimensional_analysis_card.dart';
import 'widgets/test_recommendation_box.dart';
import 'widgets/test_quote_image_block.dart';
import 'widgets/test_badge_block.dart';
import 'widgets/test_growth_path_block.dart';
import 'widgets/test_text_progress_block.dart';
import 'widgets/test_visual_meter_block.dart';

class TestDetailPage extends StatelessWidget {
  final logic = Get.put(TestDetailLogic());

  TestDetailPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // clog('daskld   ')
    return BaseGetBuilder<TestDetailLogic>(
      // appBar: ,
      backgroundView: const Positioned(
          child: Align(
        alignment: Alignment.topCenter,
        child: AutoImage(
          Assets.icomTestTopBg,
          fit: BoxFit.fitWidth,
        ),
      )),
      backgroundColor: AppColor.colorF5F7FA,
      builder: (controller) {
        return Stack(
          children: [
            Positioned.fill(
                child: SingleChildScrollView(
              controller: controller.scrollController,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w).copyWith(
                    top: 140.w + kToolbarHeight,
                    bottom: 60.w + ScreenUtil().bottomBarHeight),
                child: Column(
                  children: [
                    _buildTestCard(controller),
                    SizedBox(height: 20.w),
                    _buildTestInfoCard(controller),
                    SizedBox(height: 20.w),
                    const TestKeywordTagBlock(),
                    SizedBox(height: 20.w),
                    const TestMatchingResultBlock(),
                    SizedBox(height: 16.w),
                    TestRadarChartBlock(
                        testDetail: controller.testDetail.value),
                    SizedBox(height: 16.w),
                    TestMultiDimensionalAnalysisCard(
                        testDetail: controller.testDetail.value),
                    SizedBox(height: 16.w),
                    TestRecommendationBox(
                        testDetail: controller.testDetail.value),
                    SizedBox(height: 16.w),
                    const TestQuoteImageBlock(
                        // imageUrl: AppConfig.testImage,
                        ),
                    SizedBox(height: 16.w),
                    const TestBadgeBlock(),
                    SizedBox(height: 16.w),
                    TestGrowthPathBlock(
                      currentStage: 1,
                      testDetail: controller.testDetail.value,
                      items: const [
                        'Self-awareness',
                        'Skill Development',
                        'Practical application',
                        'Continuous optimization',
                        'Influencing Others'
                      ],
                    ),
                    SizedBox(height: 16.w),
                    const TextProgressBlock(),
                    SizedBox(height: 16.w),
                    const TestVisualMeterBlock(
                      // title: 'Comprehensive ability',
                      // subtitle: 'Comprehensive indicators',
                      // value: 60,
                      // level: 'Very high',
                      // completionRate: 82,
                      data: null,
                    ),
                    SizedBox(height: 16.w),
                  ],
                ),
              ),
            )),
            Positioned(
                bottom: ScreenUtil().bottomBarHeight,
                // bottom: ScreenUtil()(),
                right: 16.w,
                left: 16.w,
                child: CommonButton.expend(
                  title: 'Start Test',
                  onClick: () {
                    logic.startTest();
                  },
                )),
            Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Obx(() {
                  return CommonAppBar(
                    title: 'Test Details',
                    leadingImageColor: logic.isDarkTitle.value
                        ? Colors.white
                        : AppColor.color0C0A09,
                    titleColor: logic.isDarkTitle.value
                        ? Colors.white
                        : AppColor.color0C0A09,
                    backgroundColor:
                        Colors.white.withOpacity(logic.appBarOpacity),
                    actions: [
                      GestureDetector(
                        onTap: () => logic.toggleFavorite(),
                        child: Container(
                          width: 32.w,
                          height: 32.w,
                          decoration: const BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                          ),
                          alignment: Alignment.center,
                          child: Obx(() => AutoImage(
                                logic.testDetail.value.isFavorite == true
                                    ? Assets.commonCollectionEd
                                    : Assets.commonCollection,
                                width: 24.w,
                              )),
                        ),
                      ),
                      12.horizontalSpace,
                      GestureDetector(
                        onTap: () {
                          ShareBottomSheet().show();
                        },
                        child: Container(
                          width: 32.w,
                          height: 32.w,
                          decoration: const BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                          ),
                          alignment: Alignment.center,
                          child: AutoImage(
                            Assets.commonShare,
                            width: 24.w,
                          ),
                        ),
                      ),
                      16.horizontalSpace,
                    ],
                  );
                }))
          ],
        );
      },
    );
  }

  // 第一个卡片：测试卡片
  Widget _buildTestCard(TestDetailLogic controller) {
    final testDetail = controller.testDetail.value;

    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.w),
        border: Border.all(color: AppColor.colorF5F5F5),
      ),
      padding: EdgeInsets.zero,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 测试图片（如果有）
          // if (testDetail.image != null && testDetail.image!.isNotEmpty)
          //   ClipRRect(
          //     borderRadius: BorderRadius.only(
          //       topLeft: Radius.circular(20.w),
          //       topRight: Radius.circular(20.w),
          //     ),
          //     child: ImageView(
          //       imageUrl: testDetail.image!,
          //       width: double.infinity,
          //       height: 160.w,
          //       fit: BoxFit.cover,
          //     ),
          //   ),

          // 内容部分
          Padding(
            padding: EdgeInsets.all(12.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  testDetail.name ?? 'Discover the real you',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: AppColor.color0C0A09,
                  ),
                ),
                SizedBox(height: 6.w),
                Text(
                  testDetail.desc ??
                      'Gain deeper insights into your inner traits through scientific personality assessments',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: AppColor.color0C0A09.withOpacity(0.16),
                  ),
                ),
                SizedBox(height: 12.w),
                // // 用户头像和评分区域
                // Row(
                //   children: [
                //     // 头像组
                //     _buildAvatarGroup(),
                //     SizedBox(width: 4.w),
                //     Text(
                //       '1.2k+',
                //       style: TextStyle(
                //         fontSize: 12.sp,
                //         color: AppColor.color0C0A09,
                //         letterSpacing: 0.06,
                //       ),
                //     ),
                //     Spacer(),
                //     // 评分区域
                //     Row(
                //       children: [
                //         _buildStarIcon(),
                //         SizedBox(width: 4.w),
                //         Text(
                //           '4.5',
                //           style: TextStyle(
                //             fontSize: 12.sp,
                //             fontWeight: FontWeight.w500,
                //             color: AppColor.color0C0A09,
                //           ),
                //         ),
                //       ],
                //     ),
                //   ],
                // ),
                UtilsWidget.buildParticipantsAndRating(
                    logic.testDetail.value.userAvatars ?? [],
                    logic.testDetail.value.total ?? 0),
                // const Spacer(),
                // // 价格和评分
                // UtilsWidget.buildPriceAndRating(
                //     price: model.price,
                //     discountPrice: model.discountPrice,
                //     star: model.star),
                SizedBox(height: 12.w),
                // 底部价格与评分
                UtilsWidget.buildPriceAndRating(
                    price: logic.testDetail.value.price,
                    discountPrice: logic.testDetail.value.discountPrice,
                    star: logic.testDetail.value.star),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 第二个卡片：测试信息卡片
  Widget _buildTestInfoCard(TestDetailLogic controller) {
    final testDetail = controller.testDetail.value;
    final questionCount = testDetail.questionCount ?? 15;
    // final answerTimeMinutes = testDetail.answerTime != null
    //     ? (testDetail.answerTime! / 60).round()
    //     : 8;

    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.w),
      ),
      child: Column(
        children: [
          // 顶部渐变标题
          Container(
            width: double.infinity,
            height: 41.w,
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [
                  Color(0xFFFF4C97),
                  Color(0xFFFF94C1),
                ],
              ),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.w),
                topRight: Radius.circular(20.w),
              ),
            ),
            alignment: Alignment.center,
            child: Text(
              'Test Information',
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w700,
                color: Colors.white,
              ),
            ),
          ),
          // 信息内容部分
          Padding(
            padding: EdgeInsets.all(16.w),
            child: Column(
              children: [
                // 问题数量
                _buildInfoItem(
                  iconBackgroundColor: const Color(0xFFCFF0EB),
                  icon: Icons.edit,
                  title: 'Number of questions',
                  subtitle: '$questionCount questions',
                ),
                SizedBox(height: 8.w),
                // 预计时间
                _buildInfoItem(
                  iconBackgroundColor: const Color(0xFFEEF3F5),
                  icon: Icons.access_time,
                  title: 'Estimated time',
                  subtitle: '${testDetail.answerTime} minutes',
                ),
                SizedBox(height: 8.w),
                // 数据来源
                _buildInfoItem(
                  iconBackgroundColor: const Color(0xFFFBEBFB),
                  icon: Icons.swap_vert,
                  title: 'Data source',
                  subtitle: testDetail.typeName != null
                      ? 'Based on the ${testDetail.typeName} theory'
                      : 'Based on the Big Five personality theory',
                ),
                SizedBox(height: 12.w),
                const Divider(color: AppColor.colorF5F5F5),
                SizedBox(height: 12.w),
                // 标签
               SizedBox(
                 width: double.infinity,
                 child:  Wrap(
                   spacing: 8.w,
                   runSpacing: 8.w,
                   // alignment: WrapAlignment.start,
                   // runAlignment: WrapAlignment.start,
                   children: _buildTags([logic.testDetail.value.typeName ?? '']),
                 ),
               )
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建标签列表
  List<Widget> _buildTags(List<String> tags) {
    return tags.map((tag) => _buildTag(tag)).toList();
  }

  // 信息项
  Widget _buildInfoItem({
    required Color iconBackgroundColor,
    required IconData icon,
    required String title,
    required String subtitle,
  }) {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16.w),
        border: Border.all(color: iconBackgroundColor),
      ),
      child: Row(
        children: [
          Container(
            width: 32.w,
            height: 32.w,
            decoration: BoxDecoration(
              color: iconBackgroundColor,
              shape: BoxShape.circle,
            ),
            child: Icon(
              icon,
              size: 16.w,
              color: AppColor.color0C0A09,
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF0D1209),
                    letterSpacing: 0.14,
                  ),
                ),
                SizedBox(height: 4.w),
                Text(
                  subtitle,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Color(0xFF7F909F),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 标签
  Widget _buildTag(String text) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 5.w),
      decoration: BoxDecoration(
        color: Color(0xFFFBEBFB),
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 10.sp,
          color: Color(0xFFF28CDE),
        ),
      ),
    );
  }

// 第三个卡片：特征标签卡片
// Widget _buildPersonalityTypeCard(TestDetailLogic controller) {
//   final testDetail = controller.testDetail.value;
//
//   // 始终显示MatchingResultBlock组件，不依赖API数据
//   return TestMatchingResultBlock(testDetail: testDetail);
// }
}
